package com.buho29.rcmanager;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemSelectedListener;

import com.buho29.rcmanager.bd.DatabaseAdapter;
import com.buho29.rcmanager.bd.TableAlarm;
import com.buho29.rcmanager.bd.TableModel;
import com.buho29.rcmanager.bd.TableStatistic;
import com.buho29.rcmanager.utils.Make;
import com.buho29.rcmanager.utils.Format;


public class AlarmView extends ListActivity {
    
    
    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST +1;
    private static final int EDIT_ID = Menu.FIRST + 2;
	private static final int RESET_ID = Menu.FIRST + 3;
    
	private DatabaseAdapter mDbAdapter;
	private TableAlarm mDbTableAlarm= new TableAlarm();
	
	private Long mModelId;
	

	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.power_view);
        
        Bundle extras = getIntent().getExtras();            
		if(savedInstanceState != null){
	       	mModelId = savedInstanceState.getLong(TableModel.COL_ROW_ID,0);
		}else if(extras != null){
			mModelId = extras.getLong(TableModel.COL_ROW_ID,0);
		}
        
        mDbAdapter = DatabaseAdapter.getInstance(this);
        mDbTableAlarm.setSQLiteDatabase(mDbAdapter.getDatabase());
        
        TableModel m = new TableModel();
        m.setSQLiteDatabase(mDbAdapter.getDatabase());
        m.setId(mModelId);
        m.load();
        setTitle(m.getName()+">"+getText(R.string.alarm));
        
        populateFields();
        
        registerForContextMenu(getListView());
    }
    
    private void populateFields(){
        
    	Cursor cur= mDbTableAlarm.fetchModel(mModelId);
        startManagingCursor(cur);
        
        setListAdapter(new AlarmAdapter(this,cur));

		TableStatistic st = new TableStatistic();
		st.setSQLiteDatabase(mDbAdapter.getDatabase());
		
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID,0, getString(R.string.New));
        return true;
    }    
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case INSERT_ID:
        	makeDiaAlarm(0);
            return true;
	    }        
        return super.onMenuItemSelected(featureId, item);
    }
    
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, getString(R.string.delete));
        menu.add(0, EDIT_ID, 0, getString(R.string.edit));
        menu.add(0, RESET_ID, 0, getString(R.string.reset));
	}
    
    @Override
	public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch(item.getItemId()) {
	    	case DELETE_ID:
		        mDbTableAlarm.setId(info.id);
		        mDbTableAlarm.delete();
		        populateFields();
		        return true;
		    case EDIT_ID:
		    	mDbTableAlarm.setId(info.id);
		    	mDbTableAlarm.load();
		    	makeDiaAlarm(info.id);
		        return true;
		    case RESET_ID:
		    	mDbTableAlarm.setId(info.id);
		    	mDbTableAlarm.load();
		    	mDbTableAlarm.reset();
		    	mDbTableAlarm.save();
		        populateFields();
		        return true;
		}
		return super.onContextItemSelected(item);
	}
    
            
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(TableModel.COL_ROW_ID, mModelId);
    }
    
    
	private void makeDiaAlarm(final long id ) {
		LayoutInflater factory = LayoutInflater.from(this);
		View view = factory.inflate(R.layout.alarm_model, null);
		
		final EditText tName = (EditText) view.findViewById(R.id.tvName);
		final EditText tNum = (EditText) view.findViewById(R.id.tvNum);
		final Spinner sc = (Spinner) view.findViewById(R.id.sp);
		final TextView tvStep = (TextView) view.findViewById(R.id.tvStep);
		final TextView tvhelp = (TextView) view.findViewById(R.id.tvHelp);
		
		sc.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int pos, long id1) {
				if(id1 == TableAlarm.TYPE_TIME){
					tvStep.setText(getText(R.string.h));
					tvhelp.setText(getText(R.string.help_alarm_1));
				}else if (id1 == TableAlarm.TYPE_DATE){
					tvStep.setText(getText(R.string.d));
					tvhelp.setText(getText(R.string.help_alarm_2));
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {}
			
		});
		
		AlertDialog.Builder builder = new AlertDialog.Builder(AlarmView.this);
		builder.setIcon(R.drawable.alert_dialog_icon)
		.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	saveData (
            		id,
            		tName.getText().toString(),
            		Integer.parseInt(tNum.getText().toString()),
            		sc.getSelectedItemPosition()
            	);
            }
         })
         .setNegativeButton(R.string.cancel, null)
         .setView(view);
		
		if(id<1){
			tNum.setText("1");
			sc.setSelection(0);
			builder.setTitle(R.string.newAlarm);
		}else{
			tName.setText(mDbTableAlarm.getName());
			tNum.setText(String.valueOf(mDbTableAlarm.getStep()));
			sc.setSelection(mDbTableAlarm.getType());
			builder.setTitle(R.string.editAlarm);
		}	
        builder.create().show();
	}
	
	protected void saveData(long id ,String name, long step,int type) {
		
		mDbTableAlarm.setId(id);
		
		if(id<1){// new
			mDbTableAlarm.setType(type);
			mDbTableAlarm.reset();
			mDbTableAlarm.setModelId(mModelId);	
		}else{
			mDbTableAlarm.load();
			if(mDbTableAlarm.getType() != type) 
				mDbTableAlarm.reset();
			mDbTableAlarm.setType(type);
		}
		
		mDbTableAlarm.setName(name);
		mDbTableAlarm.setStep(step);
		mDbTableAlarm.save();
		populateFields();
		
	}
    
    public class AlarmAdapter extends BaseAdapter{
    	
        private Context mContext;
        private Cursor mCursor;
        
    	public AlarmAdapter(Context c ,Cursor cursor) {
            mContext = c;
            mCursor = cursor;
		}
    	
		@Override
		public int getCount() {
			return mCursor.getCount();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			mCursor.moveToPosition(position);
            return mCursor.getLong(mCursor.getColumnIndexOrThrow(TableModel.COL_ROW_ID));
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater factory = LayoutInflater.from(mContext);
			View view = factory.inflate(android.R.layout.simple_list_item_2, null);
			
			TextView tv1 = (TextView) view.findViewById(android.R.id.text1);
			TextView tv2 = (TextView) view.findViewById(android.R.id.text2);
			
			mCursor.moveToPosition(position);
			mDbTableAlarm.loadCursor(mCursor);
			
			String text = "";
			
			switch (mDbTableAlarm.getType()) {
				case TableAlarm.TYPE_TIME:
				text = getText(R.string.time)+" "+mDbTableAlarm.getStep()+" "+getString(R.string.h);
				break;
			case TableAlarm.TYPE_DATE:
				text = getText(R.string.date)+" "+mDbTableAlarm.getStep()+" "+getString(R.string.d);
				break;
			}
			tv1.setText(text);
			
			SpannableStringBuilder ss = new SpannableStringBuilder();
			Make.appendResult(ss,getText(R.string.note) ,mDbTableAlarm.getName(), Make.NEWLINE);
			
			int tl = (int) mDbTableAlarm.getTimeLeft();
			if(tl>0)
				Make.appendResult(ss,getText(R.string.timeLeft),Format.formatSecondsToString(tl),"");
			else
				Make.appendResult1(ss,getText(R.string.timeLeft),Format.formatSecondsToString(tl),"",Color.RED);
			
			tv2.setText(ss);
						
			return view;
		}
    	
    }
}